module.exports = app => {

    const express = require('express')
    const jwt = require('jsonwebtoken')
    const assert = require('http-assert')

    const User = require('../model/User')

    const router = express.Router({
        mergeParams: true
    })

    router.post('/register', async(req, res) => {
        const model = await User.create(req.body)
        res.send(model)
    })

    router.post('/login', async(req, res) => {
        const {
            username,
            password
        } = req.body

        //1、根据用户名找用户
        const user = await User.findOne({
            username: username //这里不能一起查用户密码，密码会被散列
        }).select('+password')

        assert(user, 422, "用户不存在")

        //2、验证是否正确
        const isValid = require('bcryptjs').compareSync(password, user.password)
        assert(isValid, 422, '密码错误')

        //3、返回token
        const token = jwt.sign({
            id: user._id,
        }, app.get('secret'))
        res.send({
            user: user,
            token: token
        })

    })

    app.use('/user', router)


    //错误处理函数
    app.use(async(err, req, res, next) => {
        // console.log(err);
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })

}